package development.app;

import state.GameAlert;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.SMSHandler;
import state.SendSMSListener;
import state.component.Event;
import state.component.EventListener;
import state.component.GridMenu;
import state.socket.DataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.TwoDimensionString;
import state.util.array.ObjectArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.Utils;
import development.bean.SMSServiceCommand;
import development.bean.Subscription;
import development.socket.SocketClientUtil;

public class FrmCuaHang extends GameForm implements EventListener, SendSMSListener {

  private StringArray CUAHANG_NAME;
  private StringArray CUAHANG_CATEGORY_CODE;
  private StringArray CUAHANG_CATEGORY_DATABASE;
  private TwoDimensionString CUAHANG_TOOLTIP;
  
  //Media
  public static final int GET_CATEGORY_LIST_REQUEST = 1501;
  public static final int GET_CATEGORY_LIST_RESPONSE = 1502;
  public static final int GET_CONTENT_LIST_REQUEST = 1503;
  public static final int GET_CONTENT_LIST_RESPONSE = 1504;
  public static final int GET_CATEGORY_PARENT_LIST_REQUEST = 1505;
  public static final int GET_CATEGORY_PARENT_LIST_RESPONSE = 1506;
  public static final int GET_CONTENT_DATA_REQUEST = 1507;
  public static final int GET_CONTENT_DATA_RESPONSE = 1508;
  public static final int GET_COUNT_RESPONSE = 1509;
  
  public static final int GET_DOWNLOAD_URL_RESPONSE = 1512;
  // VAS

  public static final int GET_VAS_CATEGORY_LIST_REQUEST = 1513;
  public static final int GET_VAS_CATEGORY_LIST_RESPONSE = 1514;
  public static final int GET_VAS_CONTENT_LIST_REQUEST = 1515;
  public static final int GET_VAS_CONTENT_LIST_RESPONSE = 1516;
  public static final int GET_VAS_CATEGORY_PARENT_LIST_REQUEST = 1517;
  public static final int GET_VAS_CATEGORY_PARENT_LIST_RESPONSE = 1518;

  public static final int GET_VAS_COUNT_RESPONSE = 1519;

  // download
  public static final int GET_DOWNLOAD_REQUEST = 1520;
  public static final int GET_DOWNLOAD_RESPONSE = 1521;

  private ObjectArray itemsImages;
  private int chooseIndex;
  private int HOZ_DISTANCE = 60;
  private int VER_DISTANCE = 55;
  private int DX = 30;
  private int DY = 165;
  private int NUMBER_OF_ITEM_PER_ROW = 4;
  private int numberOfItem;
  private static GameForm singleton;
  private GridMenu gridMenu;
  private StringArray type;
  private String typeOfData;
  private String urldownload;
  private String fileNameToSave;
  private StringArray arrSMSServiceCode;
  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmCuaHang();
    }
    return singleton;
  }

  public FrmCuaHang() {
    CUAHANG_NAME = new StringArray(new String[]          {     "Game Offline",        "Ứng dụng",    "Nhạc chuông",      "Theme",    "Bỏ thuốc lá",          "Mẹo vặt",     "Tìm người yêu",             "Truyện",            "Bí ẩn giấc mơ",             "Bói vui",           "Vợ chồng" }, 11);
    CUAHANG_CATEGORY_CODE = new StringArray(new String[] {     "GAME",           "UNG_DUNG",    "RING_BACK",        "THEMES",   "TV_BO_THUOC_LA",       "TV_MEO_VAT",  "TimYTrungNhan",             "TRUYEN",            "GIACMO",                         "BOI_VUI",           "CSVoChong" }, 11);
    CUAHANG_CATEGORY_DATABASE = new StringArray(new String[] { "media",               "media",       "media",            "media",    "vas",                  "vas",         "download",                  "vas",               "download",                  "vas",               "download" }, 11);
    type = new StringArray(new String[] { "media", "vas", "download" }, 3);
    
    CUAHANG_TOOLTIP = new TwoDimensionString(2, 11);
    CUAHANG_TOOLTIP.setColumn(0, new StringArray(new String[] {  "Game",             "Ứng dụng" ,    "Nhạc chuông" ,     "Theme" ,   "Bỏ thuốc lá" ,      "Mẹo vặt" ,      "Tìm ý",                    "Đọc truyện" ,        "Bí ẩn",                     "Bói vui" ,          "Cẩm nang"}, 11));
    CUAHANG_TOOLTIP.setColumn(1, new StringArray(new String[] {  "",                 "" ,            "" ,                "" ,        "" ,                  "" ,            "trung nhân",               "" ,                  "giấc mơ",                   "" ,                 "vợ chồng"}, 11));
  }

  public void init(Hashtable hashtable) {
    if (Constants.IS_240x320_SCREEN) {
      HOZ_DISTANCE = 70;
      VER_DISTANCE = 60;
      DX = 50;
      DY = 60;
      NUMBER_OF_ITEM_PER_ROW = 3;
    } else {
      HOZ_DISTANCE = 70;
      VER_DISTANCE = 60;
      DX = 50;
      DY = 60;
      NUMBER_OF_ITEM_PER_ROW = 4;
    }
    numberOfItem = CUAHANG_CATEGORY_CODE.len();
    itemsImages = ObjectArray.create(numberOfItem);

    itemsImages.set(0, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "5.Game-hot.png"));
    itemsImages.set(1, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "2.Ung-dung.png"));
    itemsImages.set(2, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "6.Nhac-chuong.png"));
    itemsImages.set(3, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "4.Theme.png"));
    itemsImages.set(4, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "4.Bothuocla.png"));
    itemsImages.set(5, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "2.Meovat.png"));
    itemsImages.set(6, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "7.Ytrungnhan.png"));
    itemsImages.set(7, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "1.Doctruyen.png"));
    itemsImages.set(8, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "5.Giacmo.png"));
    itemsImages.set(9, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "3.Boivui.png"));
    itemsImages.set(10, ImageUtil.getImage(Constants.CUA_HANG_CATEGORY, "8.Vochong.png"));

    chooseIndex = 0;
    gridMenu = new GridMenu(_manager, itemsImages, CUAHANG_NAME, NUMBER_OF_ITEM_PER_ROW, DX, DY, HOZ_DISTANCE, VER_DISTANCE, this);
    gridMenu.setToolTip(CUAHANG_TOOLTIP);
    gridMenu.setForceGroundColor(GameColor.WHITE_CODE);
    gridMenu.setFocusFgColor(GameColor.YELLOW_CODE);
    typeOfData = type.get(0);
    fileNameToSave=null;
    _manager.enableTouchPad();
  }
  
  public GridMenu getGridMenu() {
    return gridMenu;
  }

  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);
    drawMain(g);
    _manager.disableTouchPad();
  }

  private void drawMain(Graphics g) {
    DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
  }
  
  private StringArray categoryCodeToSubscriptionServiceCode(String categoryCode){
    //"GAME","UNG_DUNG","RING_BACK","THEMES","TV_BO_THUOC_LA","TV_MEO_VAT","TimYTrungNhan","TRUYEN","GIACMO","BOI_VUI","CSVoChong"
    if(categoryCode == null || categoryCode.equals("") || categoryCode.equals("GAME")){
      return new StringArray(new String[]{"GA","GA DS","Phí tải game 10 gold@@@Bạn đồng ý không?"}, 3);
    }
    if(categoryCode.equals("UNG_DUNG") || categoryCode.equals("TimYTrungNhan") || categoryCode.equals("GIACMO") || categoryCode.equals("CSVoChong")){
      return new StringArray(new String[]{"GAUD","GA UD","Phí tải ứng dụng 10 gold@@@Bạn đồng ý không?"}, 3);
    }
    if(categoryCode.equals("RING_BACK")){
      return new StringArray(new String[]{"VDHOT","VD HOT","Phí tải Clip HOT 10 gold@@@Bạn đồng ý không?"}, 3);
    }
    if(categoryCode.equals("THEMES")){
      return new StringArray(new String[]{"GATHEME", "GA THEME","Phí tải Theme 10 gold@@@Bạn đồng ý không?"}, 3);
    }
    if(categoryCode.equals("TV_BO_THUOC_LA") || categoryCode.equals("TV_MEO_VAT") || categoryCode.equals("BOI_VUI") || categoryCode.equals("BOI_VUI")){
      return new StringArray(new String[]{"GOIMV","GOI MV","Phí dịch vụ 10 gold@@@Bạn đồng ý không?"}, 3);
    }
    if(categoryCode.equals("TRUYEN")){
      return new StringArray(new String[]{"GOITRUYEN", "GOI TRUYEN","Phí dịch vụ 10 gold@@@Bạn đồng ý không?"}, 3);
    }
    return null;
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.LEFT:
      chooseIndex = (chooseIndex - 1 < 0) ? 0 : chooseIndex - 1;
      break;
    case Key.RIGHT:
      chooseIndex = (chooseIndex + 1 > numberOfItem) ? numberOfItem : chooseIndex + 1;
      break;
    case Key.DOWN:
      chooseIndex = (chooseIndex + NUMBER_OF_ITEM_PER_ROW > numberOfItem - 1) ? chooseIndex : chooseIndex + NUMBER_OF_ITEM_PER_ROW;
      break;
    case Key.UP:
      chooseIndex = (chooseIndex - NUMBER_OF_ITEM_PER_ROW < 0) ? chooseIndex : chooseIndex - NUMBER_OF_ITEM_PER_ROW;
      break;
    case Key.SOFT_RIGHT:
      parentGroup.goBack();
      break;
    case Key.ENTER:
      chooseIndex = gridMenu.getCurrentSelectedIndex();
      arrSMSServiceCode = categoryCodeToSubscriptionServiceCode(CUAHANG_CATEGORY_CODE.get(chooseIndex));
      Subscription sub = Utils.getSubcription(arrSMSServiceCode.get(0), arrSMSServiceCode.get(1));
      if (sub == null || sub.status == Subscription.EXPIRED) {
        SMSServiceCommand sms = Utils.getSMSServiceCommand(arrSMSServiceCode.get(0), arrSMSServiceCode.get(1)); 
        if(sms != null){
          Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, GameStringUtils.split(arrSMSServiceCode.get(2), "@@@") , 10000);
          return;
        }
      }
      typeOfData = CUAHANG_CATEGORY_DATABASE.get(chooseIndex);
      if (typeOfData.equalsIgnoreCase(type.get(0))) {
        DataPackage dataPackage = DataPackage.createDataPackage1(GET_CATEGORY_LIST_REQUEST);
        dataPackage.putString(CUAHANG_CATEGORY_CODE.get(chooseIndex));
        dataPackage.putInt(0);
        dataPackage.putInt(10);
        Global.appClient.write(dataPackage);
        FrmCuaHangMedia.CUAHANG_CATEGORY_CODE = CUAHANG_CATEGORY_CODE.get(chooseIndex);
        FrmCuaHangMedia.CUAHANG_NAME = CUAHANG_NAME.get(chooseIndex);
        Global.nextState(FrmCuaHangMedia.instance(), null);
      } else if (typeOfData.equalsIgnoreCase(type.get(1))) {
        if ("TV_BO_THUOC_LA".equalsIgnoreCase(CUAHANG_CATEGORY_CODE.get(chooseIndex))) {
          DataPackage dataPackage = DataPackage.createDataPackage1(GET_VAS_CONTENT_LIST_REQUEST);
          dataPackage.putString(CUAHANG_CATEGORY_CODE.get(chooseIndex));
          dataPackage.putInt(0);
          dataPackage.putInt(10);
          Global.appClient.write(dataPackage);
          FrmCuaHangVas.type = "drawContentList";
        } else {
          DataPackage dataPackage = DataPackage.createDataPackage1(GET_VAS_CATEGORY_LIST_REQUEST);
          dataPackage.putString(CUAHANG_CATEGORY_CODE.get(chooseIndex));
          dataPackage.putInt(0);
          dataPackage.putInt(10);
          Global.appClient.write(dataPackage);
          FrmCuaHangVas.type = "drawCategory";
        }
        FrmCuaHangVas.CUAHANG_CATEGORY_CODE = CUAHANG_CATEGORY_CODE.get(chooseIndex);
        FrmCuaHangVas.CUAHANG_NAME = CUAHANG_NAME.get(chooseIndex);
        Global.nextState(FrmCuaHangVas.instance(), null);
      } else {
        DataPackage dataPackage = DataPackage.createDataPackage1(GET_DOWNLOAD_REQUEST);
        dataPackage.putString(CUAHANG_CATEGORY_CODE.get(chooseIndex));
        Global.appClient.write(dataPackage);
      }
      break;
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    FrmCuaHangMedia frmCHM = (FrmCuaHangMedia) FrmCuaHangMedia.instance();
    FrmCuaHangVas frmVas = (FrmCuaHangVas) FrmCuaHangVas.instance();
    switch (header) {
    case GET_COUNT_RESPONSE:
      frmCHM.onRecieveData(dataPackage);
      break;
    case GET_CATEGORY_LIST_RESPONSE:
      frmCHM.onRecieveData(dataPackage);
      break;
    case GET_CATEGORY_PARENT_LIST_RESPONSE:
      frmCHM.onRecieveData(dataPackage);
      break;
    case GET_CONTENT_LIST_RESPONSE:
      frmCHM.onRecieveData(dataPackage);
      break;
    case GET_CONTENT_DATA_RESPONSE:
      frmCHM.onRecieveData(dataPackage);
      break;
    case GET_DOWNLOAD_RESPONSE:
      urldownload = dataPackage.nextString();
      fileNameToSave = dataPackage.nextString();
      GameGlobal.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Tải về bạn sẽ ", "phải dùng trình duyệt", "Bạn có đồng ý không?" ), 50);
      break;
    case GET_VAS_COUNT_RESPONSE:
      frmVas.onRecieveData(dataPackage);
      break;
    case GET_VAS_CATEGORY_LIST_RESPONSE:
      frmVas.onRecieveData(dataPackage);
      break;
    case GET_VAS_CONTENT_LIST_RESPONSE:
      frmVas.onRecieveData(dataPackage);
      break;
    case GET_VAS_CATEGORY_PARENT_LIST_RESPONSE:
      frmVas.onRecieveData(dataPackage);
      break;
    }
  }

  public void destroy() {
    itemsImages = null;
    gridMenu = null;
    arrSMSServiceCode = null;
  }

  public void onActionPerform(Event event) {
    if (event.getSource() == gridMenu) {
      keyReleased(Key.FIRE);
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 50 && eventType == GameAlert.YES_BUTTON) {
      doDownload(urldownload);
    }
    if (alertId == 10000 && eventType == GameAlert.YES_BUTTON) {
      SMSServiceCommand sms = Utils.getSMSServiceCommand(arrSMSServiceCode.get(0), arrSMSServiceCode.get(1));
      if (sms != null) {
        SMSHandler.getInstance(this).sendMsg(sms.serviceNumber, sms.command);
      }
    }
  }

  public void onSendSMSFail() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Gửi tin nhắn thất bại");
  }

  public void onSendSMSSuccess() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Gửi tin nhắn thành công");
    SocketClientUtil.createSubscription(arrSMSServiceCode.get(0), arrSMSServiceCode.get(1));
  }

  public void doDownload(String url) {
    Global.systemCanvas.getMidlet().platformRequest(url);
  }
  
  private class CuaHangCategory {
    String code;
    String name;
    String parent_code;
    String parentname;
    String has_child;
    String fee;
    String url_avatarimage;
    GameImage avatarimage;
  }
}